package sdk.webview.fmc.com.fmcsdk.check;

import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.AppCompatTextView;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;

import sdk.webview.fmc.com.fmcsdk.R;

public class ExpandableTextView extends AppCompatTextView {
    private static  String MORE_TEXT = "查看更多";
    private boolean isExpanded = false;
    private String fullText;

    public ExpandableTextView(Context context) {
        super(context);
        init();
    }

    private void init() {
        MORE_TEXT= getResources().getString(R.string.See_more);
        setMaxLines(2);
        setEllipsize(TextUtils.TruncateAt.END);
        setOnClickListener(v -> toggle());
    }

    public void setTextWithMore(String text) {
        this.fullText = text;
        showCollapsedText();
    }

    private void showCollapsedText() {
        Layout layout = getLayout();
        if (layout == null) {
            post(this::showCollapsedText);
            return;
        }

        int lineEnd = layout.getLineEnd(1);
        String collapsedText = fullText.substring(0, lineEnd - 4 - MORE_TEXT.length())
                + "..." + MORE_TEXT;

        SpannableString spannable = new SpannableString(collapsedText);
        spannable.setSpan(new ForegroundColorSpan(Color.RED),
                collapsedText.length() - MORE_TEXT.length(),
                collapsedText.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        setText(spannable);
    }

    private void toggle() {
        isExpanded = !isExpanded;
        if (isExpanded) {
            setMaxLines(Integer.MAX_VALUE);
            setText(fullText);
        } else {
            setMaxLines(2);
            showCollapsedText();
        }
    }
}
